<div class="content">
	<textarea id="pre">
		const fs = require('fs')
const cheerio = require('cheerio')
const superagent = require('superagent')
const request = require('request')
const url = ''; //爬取网站链接
// 首页图片

var imgList = [];
superagent.get(url)
    .end((err, res) => {
        if (err) {
            return console.error(err)
        }
        let $ = cheerio.load(res.text);
        let imgs = $('img');
        imgs.each((index, item) => {
            let src = $(item).attr('src');
            imgList.push(src);
        });

        mkdir('./imgs', downloadImg(imgList))

    })


function downloadImg(imgList) {
    imgList.forEach((imgUrl) => {
        //获取图片名 
        let imgName = imgUrl.split('/').pop();

        //下载图片存放到指定目录
        let stream = fs.createWriteStream(`./imgs/${imgName}`);

        let req = request.get(url + imgUrl); //响应流
        req.pipe(stream);
        console.log(`开始下载图片 https:${imgUrl} --> ./imgs/${imgName}`);
    })
}

//创建目录
function mkdir(_path, callback) {
    if (fs.existsSync(_path)) {
        console.log(`${_path}目录已存在`)
    } else {
        fs.mkdir(_path, (error) => {
            if (error) {
                return console.log(`创建${_path}目录失败`);
            }
            console.log(`创建${_path}目录成功`)
        })
    }
    if (typeof callback == 'function') {
        callback(); //没有生成指定目录不会执行
    }
}

	</textarea>
</div>